package aml.bs.spring;

import com.alibaba.nacos.api.config.annotation.NacosValue;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

/**
 * @Title: SpringNacosClient
 * @Author duxuqiang02
 * @Date 2023/9/17 15:22
 * @description: Spring容器接管
 */
@Component
@Slf4j
public class SpringNacosCtxHolder {

//    @NacosValue(value = "${my-group.my-data-id:jdbc:mysql://localhost:3306/mydb}", autoRefreshed = true)
//    private String databaseUrl;

    @NacosValue(value = "${your.groupId.your.dataId:default-value}", autoRefreshed = true)
    private String config1Service;
    @NacosValue(value = "${your.dataid:default-value}", autoRefreshed = true)
    private String config2Service;

    //根据字段名反射
    public String getValue(String dataId,String defaultV){
        try {
            Field field = this.getClass().getField(dataId);
            field.setAccessible(true);
            try {
                String value = (String) field.get(this);
                if (StringUtils.isBlank(value)){
                    return defaultV;
                }
                return value;
            } catch (IllegalAccessException e) {
                log.warn("filed:{} 获取失败",dataId);
                throw new RuntimeException(e);
            }
        } catch (NoSuchFieldException e) {
            log.warn("filed:{} 获取失败",dataId);
            throw new RuntimeException(e);
        }
    }


    public String getValue(String dataId){
        try {
            Field field = this.getClass().getField(dataId);
            field.setAccessible(true);
            try {
                return (String) field.get(this);
            } catch (IllegalAccessException e) {
                log.warn("filed:{} 获取失败",dataId);
                throw new RuntimeException(e);
            }
        } catch (NoSuchFieldException e) {
            log.warn("filed:{} 获取失败",dataId);
            throw new RuntimeException(e);
        }
    }

}
